<script lang="ts" setup>
import { ref } from 'vue'
import { contrimAddSerive } from '@/api/contrim.js'
import type { UploadProps, UploadUserFile } from 'element-plus'
const dialogFormVisible = ref(false)


const fileList = ref<any[]>([])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile:any) => {
  fileList.value.push(uploadFile.raw )
}
const emit = defineEmits(['success'])
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (uploadFile) => {

    // // 基于FileReader读取图片做预览(base64格式数据)
    // const reader = new FileReader()
    // reader.readAsDataURL(uploadFile.raw)
    // reader.onload = ()=>{
    //   imageUrl.value = reader.result
    // }
 fileList.value.push(uploadFile)
 
}
const beforeRemove = (uploadFile:any, uploadFiles:any) => {
  ElMessage({
    message: '上传文件不能超过三个',
    type: 'warning',
    plain: true,
  })
}

const open = ()=>{
    dialogFormVisible.value = true
}
const uploadText =async ()=>{
  if(fileList.value.length === 0){
    return ElMessage.warning('至少需要上传一个文件！')
  }
   const fd = new FormData()
    // 关键步骤：遍历文件列表添加到FormData
    fileList.value.forEach(file => {
    fd.append('files', file.raw!)
  })

    try {
    const response = await contrimAddSerive(fd)
    ElMessage.success('上传成功')
    emit('success')
    dialogFormVisible.value = false
  } catch (error) {
    ElMessage.error('上传失败')
    console.error(error)
  } 

   dialogFormVisible.value = false
}
defineExpose({
    open
})



</script>



<template>

 <el-dialog  v-model="dialogFormVisible" title="上传文件" width="500">
    <el-form >
      <el-form-item  >
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
     multiple
     :auto-upload="false"
    :before-upload="handlePreview"
    :on-change="handleAvatarSuccess"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="3"
    :on-exceed="handleExceed"
  >
    <el-button type="primary">上传</el-button>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500KB.
      </div>
    </template>
  </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button  @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary"  @click="uploadText">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>


<style lang="scss" scoped>
</style>